<?php

namespace lib;

use Illuminate\Database\Capsule\Manager as Capsule;

class Application
{
    private $start = 0;
    private $config;

    private function startup()
    {

        header("Access-Control-Allow-Origin:*");
        header("Access-Control-Allow-Methods: PUT,POST,GET,OPTIONS,DELETE");
        header("Access-Control-Allow-Headers: Authorization, Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie");
        header('Access-Control-Max-Age:86400000');
        if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            exit;
        }
        $this->start  = microtime(true);
        $this->config = getConfig();
    }

    public function run()
    {
        $this->startup();
        $this->_initCache();
        $this->_initDatabase();
        preg_match_all('#[/?](\w+)?#', $_SERVER['REQUEST_URI'], $params);
        $controller = empty($params[1][0]) ? 'Index' : ucfirst($params[1][0]);
        $action     = empty($params[1][1]) ? 'index' : $params[1][1];
        Container::get($controller, $params[1])->$action();
        $this->shutdown();
    }

    public function _initCache()
    {
        if ($this->config->cache->enable) {
            define('CACHE_ENABLE', true);
            define('CACHE_KEY_PREFIX', $this->config->cache->prefix);
        } else {
            define('CACHE_ENABLE', false);
        }
    }

    public function _initDatabase()
    {
        $capsule = new Capsule;
        $capsule->addConnection(object_to_array($this->config->database));
        $capsule->setAsGlobal();
        $capsule->bootEloquent();
    }

    public function shutdown()
    {
        $time = round(microtime(true) - (float)($this->start), 5);
        if ($time > 1) {
            Log::out('[慢页面]' . $_SERVER['REQUEST_URI'] . ':' . $time . ':' . (memory_get_usage(true) / 1024) . 'kb', 'benchmark');
        }
        Container::clear();
    }

}
